import { namespace } from 'vuex-class'
import Vue from 'vue'

export default class Storage {
  get<T> (key: string, namespace?: string): T | undefined {
    const k = this.resolveKey(key, namespace)
    const item = localStorage.getItem(k)
    if (item) return JSON.parse(item)
    return undefined
  }

  set<T> (key: string, value: T, namespace?: string) {
    const k = this.resolveKey(key, namespace)
    if (value === undefined || value === null) {
      localStorage.removeItem(k)
    } else {
      const text = JSON.stringify(value)
      localStorage.setItem(k, text)
    }
  }

  resolveKey (key: string, namespace?: string) {
    const ns = namespace || Vue.prototype.$auth.principle?.user?.id || 'none'
    return 'rawa-document_' + ns + '_' + key
  }
}
